package com.wyz.note.project.demo;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @author: wei yz
 * @Date: 2024/1/28 15:35
 */
public class MergedCellInfoExtractor2 {
    public static void main(String[] args) throws IOException {
        // 打开Excel文件
        FileInputStream fis = new FileInputStream("D:\\test\\java\\test.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

        // 获取从第2行到第18行，第二列的合并单元格信息
        List<CellInfo> cellInfos = getCellMergeInfo(sheet, 34, 48, 0); // 列索引为1（第二列），行索引需要调整为从0开始

        // 输出结果
        System.out.println("单元格信息（包括合并与非合并）:");
        for (CellInfo info : cellInfos) {
           String stringCellValue = sheet.getRow(info.getRow()).getCell(1).getStringCellValue();
            System.out.println("单元格数据：" + stringCellValue + ", 单元格行号: " + (info.getRow() + 1) + ", 合并行数: " + info.getMergedRows());
        }

        // 关闭工作簿和文件输入流
        workbook.close();
        fis.close();
    }

    public static List<CellInfo> getCellMergeInfo(XSSFSheet sheet, int startRow, int endRow, int colIndex) {
        List<CellInfo> cellInfos = new ArrayList<>();

        int numMergedRegions = sheet.getNumMergedRegions();
        List<Integer> mergedRows = new ArrayList<>(); // 用于标记已经合并的行

        // 先处理合并单元格
        for (int i = 0; i < numMergedRegions; i++) {
            CellRangeAddress mergedRegion = sheet.getMergedRegion(i);

            int mergedFirstRow = mergedRegion.getFirstRow();
            int mergedLastRow = mergedRegion.getLastRow();
            int mergedFirstCol = mergedRegion.getFirstColumn();
            int mergedLastCol = mergedRegion.getLastColumn();

            // 检查合并区域是否在指定的列范围内，且行范围有重叠
            if (mergedFirstCol <= colIndex && colIndex <= mergedLastCol &&
                    (mergedFirstRow <= endRow && mergedLastRow >= startRow)) {

                // 计算合并区域与指定行范围的交集
                int intersectionStartRow = Math.max(mergedFirstRow, startRow);
                int intersectionEndRow = Math.min(mergedLastRow, endRow);

                // 添加到结果列表中
                for (int j = intersectionStartRow; j <= intersectionEndRow; j++) {
                    if (!mergedRows.contains(j)) {
                        mergedRows.add(j);
                        cellInfos.add(new CellInfo(j, intersectionEndRow - intersectionStartRow + 1));
                    }
                }
            }
        }

        // 处理非合并单元格
        for (int i = startRow; i <= endRow; i++) {
            if (!mergedRows.contains(i)) {
                cellInfos.add(new CellInfo(i, 1)); // 非合并单元格合并为1行
            }
        }

        return cellInfos;
    }

    // 辅助类，用于存储单元格的行号和合并行数
    public static class CellInfo {
        private int row;
        private int mergedRows;

        public CellInfo(int row, int mergedRows) {
            this.row = row;
            this.mergedRows = mergedRows;
        }

        public int getRow() {
            return row;
        }

        public int getMergedRows() {
            return mergedRows;
        }
    }
}
